// 当DOM加载完成后执行
document.addEventListener('DOMContentLoaded', async function() {
    // 初始化网站
    await initWebsite();
    
    // 添加页面交互效果
    setupInteractions();
});

// 初始化网站
async function initWebsite() {
    try {
        // 加载配置
        const config = await DataLoader.loadConfig();
        if (config) {
            updateSiteConfig(config);
        }
        
        // 根据当前页面URL加载不同内容
        const currentPage = getCurrentPage();
        
        if (currentPage === 'index') {
            // 首页
            await loadIndexPageData();
        } else if (currentPage === 'album') {
            // 相册页
            // await loadAlbumPageData();
        } else if (currentPage === 'diary') {
            // 日志页
            // await loadDiaryPageData();
        } else if (currentPage === 'memory') {
            // 纪念日页
            // await loadMemoryPageData();
        }
    } catch (error) {
        console.error('初始化网站时出错:', error);
    }
}

// 获取当前页面
function getCurrentPage() {
    const path = window.location.pathname;
    const page = path.split('/').pop();
    
    if (page === '' || page === 'index.html') {
        return 'index';
    } else if (page === 'album.html') {
        return 'album';
    } else if (page === 'diary.html') {
        return 'diary';
    } else if (page === 'memory.html') {
        return 'memory';
    }
    
    return 'index';
}

// 更新站点配置
function updateSiteConfig(config) {
    // 更新页面标题
    document.title = config.siteTitle;
    
    // 更新站点名称
    const siteTitle = document.getElementById('site-title');
    if (siteTitle) {
        siteTitle.textContent = config.siteTitle.split(' - ')[0];
    }
    
    // 更新情侣信息
    updateCoupleInfo(config.couple);
    
    // 更新页脚信息
    updateFooter(config.footerText);
    
    // 计算在一起的天数
    calculateDaysTogether(config.loveStartDate);
}

// 更新情侣信息
function updateCoupleInfo(couple) {
    // 更新男生信息
    const boyName = document.getElementById('boy-name');
    const boyAvatar = document.getElementById('boy-avatar');
    
    if (boyName && couple.boy) {
        boyName.textContent = couple.boy.name;
    }
    
    if (boyAvatar && couple.boy && couple.boy.avatar) {
        boyAvatar.src = couple.boy.avatar;
        boyAvatar.alt = couple.boy.name;
    }
    
    // 更新女生信息
    const girlName = document.getElementById('girl-name');
    const girlAvatar = document.getElementById('girl-avatar');
    
    if (girlName && couple.girl) {
        girlName.textContent = couple.girl.name;
    }
    
    if (girlAvatar && couple.girl && couple.girl.avatar) {
        girlAvatar.src = couple.girl.avatar;
        girlAvatar.alt = couple.girl.name;
    }
}

// 更新页脚信息
function updateFooter(footerText) {
    const copyright = document.getElementById('copyright');
    const slogan = document.getElementById('slogan');
    
    if (copyright && footerText.copyright) {
        copyright.textContent = footerText.copyright;
    }
    
    if (slogan && footerText.slogan) {
        slogan.textContent = footerText.slogan;
    }
}

// 计算在一起的天数
function calculateDaysTogether(startDateStr) {
    // 恋爱开始的日期
    const startDate = new Date(startDateStr);
    const today = new Date();
    
    // 计算相差的毫秒数并转换为天数
    const timeDiff = Math.abs(today.getTime() - startDate.getTime());
    const daysTogether = Math.floor(timeDiff / (1000 * 3600 * 24));
    
    // 更新页面上的天数显示
    const daysElement = document.getElementById('days-together');
    if (daysElement) {
        daysElement.textContent = daysTogether;
    }
    
    // 更新纪念日页面上的总天数
    const totalDaysElement = document.getElementById('total-days');
    if (totalDaysElement) {
        totalDaysElement.textContent = daysTogether;
    }
}

// 加载首页数据
async function loadIndexPageData() {
    try {
        // 加载特性数据
        const featuresData = await DataLoader.loadFeatures();
        if (featuresData) {
            updateFeatures(featuresData);
        }
        
        // 加载时刻数据
        const momentsData = await DataLoader.loadMoments();
        if (momentsData) {
            updateMoments(momentsData);
        }
    } catch (error) {
        console.error('加载首页数据时出错:', error);
    }
}

// 更新特性部分
function updateFeatures(featuresData) {
    const featuresTitle = document.getElementById('features-title');
    const featureCards = document.getElementById('feature-cards');
    
    if (!featureCards) return;
    
    // 清空特性区域
    featureCards.innerHTML = '';
    
    // 更新标题
    if (featuresTitle && featuresData.sectionTitle) {
        featuresTitle.textContent = featuresData.sectionTitle;
    }
    
    // 添加特性卡片
    featuresData.features.forEach(feature => {
        const card = document.createElement('div');
        card.className = 'feature-card';
        
        card.innerHTML = `
            <div class="icon">
                <i class="fas fa-${feature.icon}"></i>
            </div>
            <h3>${feature.title}</h3>
            <p>${feature.description}</p>
        `;
        
        featureCards.appendChild(card);
    });
}

// 更新时刻部分
function updateMoments(momentsData) {
    const momentsTitle = document.getElementById('moments-title');
    const momentsGrid = document.getElementById('moments-grid');
    
    if (!momentsGrid) return;
    
    // 清空时刻区域
    momentsGrid.innerHTML = '';
    
    // 更新标题
    if (momentsTitle && momentsData.sectionTitle) {
        momentsTitle.textContent = momentsData.sectionTitle;
    }
    
    // 添加时刻卡片
    momentsData.moments.forEach(moment => {
        const card = document.createElement('div');
        card.className = 'moment-card';
        
        card.innerHTML = `
            <div class="moment-image">
                <img src="${moment.image}" alt="${moment.title}">
            </div>
            <div class="moment-info">
                <h3>${moment.title}</h3>
                <p class="date">${DataLoader.formatDate(moment.date)}</p>
                <p class="description">${moment.description}</p>
            </div>
        `;
        
        momentsGrid.appendChild(card);
    });
}

// 设置页面交互效果
function setupInteractions() {
    // 添加平滑滚动效果
    addSmoothScrolling();
    
    // 添加导航栏固定效果
    setupStickyNavigation();
    
    // 添加响应式导航
    setupResponsiveNavigation();
}

// 平滑滚动到锚点
function addSmoothScrolling() {
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function(e) {
            e.preventDefault();
            
            const targetId = this.getAttribute('href');
            if (targetId === '#') return;
            
            const targetElement = document.querySelector(targetId);
            if (targetElement) {
                window.scrollTo({
                    top: targetElement.offsetTop - 80,
                    behavior: 'smooth'
                });
            }
        });
    });
}

// 导航栏固定效果
function setupStickyNavigation() {
    const header = document.querySelector('header');
    const headerOffset = header ? header.offsetTop : 0;
    
    window.addEventListener('scroll', () => {
        if (window.pageYOffset > headerOffset) {
            header.classList.add('sticky');
        } else {
            header.classList.remove('sticky');
        }
    });
}

// 显示通知
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.innerHTML = `
        <div class="notification-content">
            <p>${message}</p>
            <button class="close-notification">&times;</button>
        </div>
    `;
    
    document.body.appendChild(notification);
    
    // 显示动画
    setTimeout(() => {
        notification.classList.add('show');
    }, 10);
    
    // 自动关闭
    setTimeout(() => {
        notification.classList.remove('show');
        setTimeout(() => {
            notification.remove();
        }, 300);
    }, 5000);
    
    // 手动关闭
    notification.querySelector('.close-notification').addEventListener('click', () => {
        notification.classList.remove('show');
        setTimeout(() => {
            notification.remove();
        }, 300);
    });
}

// 工具函数：格式化日期
function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    
    return `${year}年${month}月${day}日`;
}

// 工具函数：计算两个日期之间的天数
function daysBetween(date1, date2) {
    const oneDay = 24 * 60 * 60 * 1000; // 一天的毫秒数
    const diffTime = Math.abs(date2.getTime() - date1.getTime());
    return Math.round(diffTime / oneDay);
}

// 工具函数：从日期获取友好的相对时间描述
function getRelativeTimeDescription(date) {
    const now = new Date();
    const diffDays = daysBetween(now, date);
    
    if (diffDays === 0) {
        return '今天';
    } else if (diffDays === 1) {
        return date > now ? '明天' : '昨天';
    } else if (diffDays < 7) {
        return date > now ? `${diffDays}天后` : `${diffDays}天前`;
    } else if (diffDays < 30) {
        const weeks = Math.floor(diffDays / 7);
        return date > now ? `${weeks}周后` : `${weeks}周前`;
    } else if (diffDays < 365) {
        const months = Math.floor(diffDays / 30);
        return date > now ? `${months}个月后` : `${months}个月前`;
    } else {
        const years = Math.floor(diffDays / 365);
        return date > now ? `${years}年后` : `${years}年前`;
    }
}

// 移动端菜单切换
const menuToggle = document.querySelector('.menu-toggle');
if (menuToggle) {
    menuToggle.addEventListener('click', function() {
        const nav = document.querySelector('nav');
        if (nav) {
            nav.classList.toggle('active');
            this.classList.toggle('active');
        }
    });
}

// 添加响应式导航
function setupResponsiveNavigation() {
    const nav = document.querySelector('nav');
    const menuToggle = document.querySelector('.menu-toggle');
    
    if (menuToggle && nav) {
        menuToggle.addEventListener('click', function() {
            nav.classList.toggle('active');
            this.classList.toggle('active');
        });
    }
    
    // 窗口大小变化时重新检查
    window.addEventListener('resize', function() {
        if (window.innerWidth > 768 && nav) {
            nav.classList.remove('active');
            if (menuToggle) {
                menuToggle.classList.remove('active');
            }
        }
    });
}

// 初始化时也调用一次
window.addEventListener('load', setupResponsiveNavigation); 